package com.winning.pmph.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winning.pmph.entity.Book;
import com.winning.pmph.service.BookService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

public class BookExcelUtil {

    private static BookService bookService = ApplicationContextUtil.getBean(BookService.class);

    public static void uploadExcelCallback(String sourFolderPath, List<String> files) throws IOException {
        // 准备map;
        Map<String, JSONObject> isbn2MetadataMap = new HashMap<>();
        for (int i = 0; i < files.size(); i++) {
            String fileName = files.get(i);
            File file = new File(sourFolderPath + "/" + fileName);
            FileInputStream fileInputStream = new FileInputStream(file);
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
            for (int j = 0; j < xssfWorkbook.getNumberOfSheets(); j++) {
                XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(j);
                String sheetName = xssfSheet.getSheetName();
                for (int k = 1; k < xssfSheet.getPhysicalNumberOfRows(); k++) {
                    XSSFRow xssfRow = xssfSheet.getRow(k);
                    String isbn = xssfRow.getCell(0).getStringCellValue();
                    String markupPath = xssfRow.getCell(1).getStringCellValue();
                    String value = xssfRow.getCell(2).getStringCellValue();
                    // 校验参数;
                    checkParameter(fileName, sheetName, k, isbn, markupPath, value);
//                    updateBookMetadata(isbn, markupPath, value);
                    if (Objects.isNull(isbn2MetadataMap.get(isbn))) {
                        Book dbBook = bookService.lambdaQuery().eq(Book::getIsbn, isbn).one();
                        if (Objects.nonNull(dbBook)) {
                            throw new RuntimeException("图书isbn:" + isbn + "不存在");
                        }
                        isbn2MetadataMap.put(isbn, dbBook.getMetadata());
                    }
                    setMetadataValue(isbn2MetadataMap.get(isbn), markupPath, value);
                }
            }
        }
        bookService.batchUpdateMetadata(isbn2MetadataMap);
    }

    public static void setMetadataValue(JSONObject jsonObject, String markupPath, String value) {
        JSONObject cntField = jsonObject;
        String[] split = markupPath.split("/");
        for (int i = 0; i < split.length; i++) {
            String fieldName = split[i];
            if ("Creator".equals(fieldName) || "Contributor".equals(fieldName)) {
                String[] values = value.split("/");
                Map<String, String> newCreator = new LinkedHashMap<>();
                newCreator.put("Name", values[0]);
                newCreator.put("Role", values[1]);
                newCreator.put("Institution", values[2]);
                ((JSONArray) cntField.get(fieldName)).add(newCreator);
                return;
            }
            if (i == split.length - 1) {
                cntField.put(fieldName, value);
                return;
            }
            Object fieldValue = cntField.get(fieldName);
            if (Objects.isNull(fieldValue)) {
                cntField.put(fieldName, new JSONObject());
                cntField = (JSONObject) cntField.get(fieldName);
            } else if (fieldValue instanceof JSONArray) {
                cntField = new JSONObject();
                ((JSONArray) fieldValue).add(cntField);
            } else if (fieldValue instanceof JSONObject) {
                cntField = (JSONObject) fieldValue;
            }
        }

    }

    public static void checkParameter(String fileName, String sheetName, int k, String isbn, String markupPath, String value) throws RuntimeException {
        if (StringUtils.isEmpty(isbn)) {
            throw new RuntimeException("文件:" + fileName + ", 页签:" + sheetName + ", 第" + (k + 1) + "行isbn为空");
        } else if (StringUtils.isEmpty(markupPath)) {
            throw new RuntimeException("文件:" + fileName + ", 页签:" + sheetName + ", 第" + (k + 1) + "行markup的值为空");
        } else if (StringUtils.isEmpty(value)) {
            throw new RuntimeException("文件:" + fileName + ", 页签:" + sheetName + ", 第" + (k + 1) + "行value的值为空");
        }
        if (markupPath.endsWith("Creator") || markupPath.endsWith("Contributor")) {
            if (value.split("/").length != 3) {
                throw new RuntimeException("文件:" + fileName + ", 页签:" + sheetName + ", 第" + (k + 1) + "行Creator|Contributor的值不符合格式要求");
            }
        }
    }
}